"""
包含用户相关的数据库操作
"""
from sqlalchemy.orm import Session
from typing import Optional, List, Type
from backend.app.models.user import User
from backend.app.utils.logger import logger
from backend.app.utils.auth import get_password_hash, verify_password as auth_verify_password

def get_user(db: Session, user_id: int) -> Optional[User]:
    """根据ID获取用户"""
    return db.query(User).filter(User.id == user_id).first()

def get_users(db: Session, skip: int = 0, limit: int = 100) -> list[Type[User]]:
    """获取用户列表"""
    return db.query(User).offset(skip).limit(limit).all()

def get_user_by_username(db: Session, username: str) -> Optional[User]:
    """根据用户名获取用户"""
    return db.query(User).filter(User.username == username).first()

def get_user_by_phone(db: Session, phone: str) -> Optional[User]:
    """根据手机号获取用户"""
    return db.query(User).filter(User.phone == phone).first()

def get_user_by_email(db: Session, email: str) -> Optional[User]:
    """根据邮箱获取用户"""
    return User.get_by_email(db, email)

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码"""
    return auth_verify_password(plain_password, hashed_password)

def create_user(db: Session, email: str, password: str, username: str = None) -> User:
    """创建新用户"""
    try:
        # 生成密码哈希
        password_hash = get_password_hash(password)
        
        # 创建用户对象
        user = User(
            email=email,
            password_hash=password_hash,
            username=username or email.split('@')[0],  # 如果没有提供用户名，使用邮箱前缀
            is_active=True  # 新用户默认为活跃状态
        )
        
        # 添加到数据库
        db.add(user)
        db.commit()
        db.refresh(user)
        
        logger.info(f"用户创建成功: {user.email}")
        return user
        
    except Exception as e:
        db.rollback()
        logger.error(f"创建用户失败: {str(e)}")
        raise

def update_user(db: Session, email: str, **kwargs) -> Optional[User]:
    """更新用户信息"""
    try:
        user = get_user_by_email(db, email)
        if not user:
            return None
        
        # 更新密码需要特殊处理
        if "password" in kwargs:
            kwargs["password_hash"] = get_password_hash(kwargs.pop("password"))
        
        for key, value in kwargs.items():
            if hasattr(user, key):
                setattr(user, key, value)
        
        db.commit()
        db.refresh(user)
        return user
    except Exception as e:
        db.rollback()
        logger.error(f"更新用户信息失败: {str(e)}", exc_info=True)
        raise

def authenticate_user(db: Session, username: str, password: str) -> Optional[User]:
    """验证用户"""
    logger.info(f"尝试验证用户: {username}")
    user = get_user_by_username(db, username)
    if not user:
        logger.warning(f"验证失败: 用户名 {username} 不存在")
        return None
        
    logger.info(f"找到用户: {username}, 验证密码")
    if not verify_password(password, user.password_hash):
        logger.warning(f"验证失败: 用户 {username} 的密码不正确")
        return None
        
    logger.info(f"用户 {username} 验证成功")
    return user 
